package controller;

import com.github.pagehelper.PageInfo;
import entity.Admin;
import entity.LayRequest;
import entity.MyResult;
import entity.Role;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import service.AdminService;
import service.RoleService;

import javax.servlet.http.HttpSession;
import javax.xml.bind.ValidationEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bigpeng
 * @create 2020-06-09-10:25
 */
@Controller
@RequestMapping("/admin")
public class AdminController  {
    @Autowired
    private RoleService roleService;
    @Autowired(required = false)
    private AdminService adminService;

    @RequestMapping("/toAdd")
    public String toAdd(ModelMap modelMap){
        //查询所有的角色信息
        List<Role> roles = roleService.selectAll();
        //将角色信息返回到前台页面
        modelMap.addAttribute("roles",roles);
        return "add.jsp";
    }
    //method 指定http请求的方式
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Admin admin,HttpSession session){
        //todo 获取sesison中的当前登录用户，并设为操作人
        adminService.insert(admin);
        return "redirect:list";//重定向到列表页面
    }
    //@RequestParam 用来获取前台传递的值，如果指定name属性，那么只获取对应name的数据，
    //                                  如果没有指定则获取所有的
    @RequestMapping("/list")
    public String list(@RequestParam Map<String,Object> map, ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> adminPageInfo = adminService.selectByPage(map);
        //将分页查询结果传递到页面
        modelMap.addAttribute("page",adminPageInfo);
        //回传查询条件
        modelMap.addAttribute("params",map);
        return "list.jsp";
    }

    @ResponseBody
    @RequestMapping("/layList")
    public MyResult<List<Admin>> layList(LayRequest layRequest,ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> adminPageInfo = adminService.selectByPage(layRequest);
        //将分页查询结果传递到页面
        return new MyResult<>(0,adminPageInfo.getTotal(),adminPageInfo.getList());
    }


//    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    @ResponseBody//表示返回json数据，会将返回的对象转换成json格式
    @GetMapping("/delete")
    public MyResult delete(Integer id){
        boolean flag = adminService.delete(id);
        return flag?new MyResult(200,"删除成功！")
                    :new MyResult(500,"删除失败！");
    }
    // 在方法参数中定义HttpSession，HttpServletRequest,HttpServletResponse等对象 ，
    // springmvc会自动注入该对象
    @PostMapping("/login")
    public String login(String account, String password, HttpSession session){
        //根据用户名查询是否存在该用户
        Admin admin = adminService.selectByAccount(account);
        if(admin!=null&&admin.getPassword().equals(password)){
            //将用户信息放入session
            session.setAttribute("admin",admin);
            //查询用户拥有的菜单
            Role role = roleService.selectById(admin.getRoleid());
            //将角色和权限信息存放到session域
            session.setAttribute("role",role);
            return "redirect:/index.jsp";//跳转到首页
        }
        return "/login.jsp"; //以/开头为绝对路径，/对应webapp目录
    }

    //MultipartFile 对象来接收上传的文件， 参数名与input的name一致
    //@SessionAttribute("admin")  获取session域中的值
    //@RequestParam(required = false) 指定对应的参数可以为null，不是必须有值。
    @PostMapping("/headpic")
    public String headPic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException {
        System.out.println(id);
        String filename = headpic.getOriginalFilename();
        System.out.println("上传的文件名："+filename);
        File file=new File("E:/headpic/"+filename);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();//如果父目录不存在，创建该目录
        }
        //保存文件,将上传的文件内容写入file
        headpic.transferTo(file);
        admin=new Admin(id);
        //将头像访问路径保存到对象中
        admin.setHeadpic("/head/"+filename);
        //更新用户头像信息
        adminService.updateHeadPic(admin);
        return "redirect:list";
    }

    @GetMapping("/headpicDownload")
    public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException {
        //1.定位到文件地址
        File file =new File("E:/headpic/"+filename);
        //2.读取文件内容
        byte[] bytes = FileUtils.readFileToByteArray(file);
        //3. 设置http响应头
        HttpHeaders headers=new HttpHeaders();
        // 设置ContentType为stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置以附件形式打开
        headers.setContentDispositionFormData("attachment",filename);
        //                                内容   头部信息  http状态码
        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
    }


}
